<template>
  <div class="page-box">
    <div class="title">欢迎使用点餐系统</div>
    <div class="form-box">
      <div class="sub-title">手机号</div>
      <el-input v-model="form.mobile" placeholder="请输入手机号" />
      <div class="sub-title">验证码</div>
      <div class="verify-code">
        <el-input v-model="form.smsCode" placeholder="请输入验证码" />
        <el-button class="verify-btn" v-if="count === 0" type="primary" @click="getSmsCode">获取验证码</el-button>
        <el-button class="verify-btn" v-else type="primary">{{ count }}s</el-button>
      </div>
    </div>
    <div class="btn-box">
      <el-button type="primary" @click="login1">登录</el-button>
      <el-button type="info" @click="login2">游客登录</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useMobileStore } from "@/stores/modules/mobile";
import { login, getCode } from "@/api/modules/mobile";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();

const form = ref<any>({
  mobile: "",
  smsCode: ""
});
const count = ref<number>(0);
const timer = ref<any>();
const getSmsCode = async () => {
  if (!form.value.mobile) {
    ElMessage({
      type: "error",
      message: `请填写手机号!`
    });
  }
  await getCode({ phone: form.value.mobile });
  count.value = 60;
  timer.value = setInterval(() => {
    count.value = count.value - 1;
    if (count.value === 0) {
      clearInterval(timer.value);
    }
  }, 1000);
};

const login1 = async () => {
  const params = {
    phone: form.value.mobile,
    code: form.value.smsCode
  };
  const { data } = await login(params);
  if (data) {
    useMobileStore().setUserId(data.id);
    useMobileStore().setUserAvatar(data.avatar);
    useMobileStore().setUserName(data.name);
    router.replace("/mobile/home");
  }
};

const login2 = () => {
  useMobileStore().setUserId(1);
  router.replace("/mobile/home");
};
</script>
<style lang="scss" scoped>
.page-box {
  width: 100%;
  height: 100%;
  .title {
    width: 100%;
    margin-top: 24%;
    font-size: 24px;
    font-weight: 500;
    color: #000000;
    text-align: center;
  }
  .form-box {
    width: calc(100% - 72px);
    padding: 32px;
    margin-top: 36px;
    .sub-title {
      margin-top: 24px;
      margin-bottom: 12px;
      font-size: 16px;
      color: #1a2024;
    }
    .verify-code {
      display: flex;
      width: 100%;
      .verify-btn {
        margin-left: 12px;
      }
    }
  }
  .btn-box {
    display: flex;
    justify-content: center;
    width: 100%;
  }
}
</style>
